package com.yanshaohui.springboot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.yanshaohui.springboot.entity.primary.UserEntity;
import com.yanshaohui.springboot.repository.primary.UserRepository;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
public class UserController {

	@Autowired
	private UserRepository userRepository;
	
	@ApiOperation(value="获取用户列表", notes="")
	@GetMapping("/user")
	public List<UserEntity> findAll(){
		return userRepository.findAll();
	}
	
    @ApiOperation(value="获取用户详细信息", notes="根据用户名来获取用户详细信息")
    @ApiImplicitParam(name = "userName", value = "用户名字", paramType="path",required = true, dataType = "String")
	@GetMapping("/user/{userName}")
	public UserEntity findOne(@PathVariable("userName") String userName){
		return userRepository.findByUserName(userName);
	}
	
	@ApiOperation(value="创建用户", notes="根据UserEntity对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "UserEntity")
	@PostMapping("/user")
	public UserEntity add(@RequestBody UserEntity user){
		return userRepository.saveAndFlush(user);
	}
	
    @ApiOperation(value="更新用户详细信息", notes="根据url的id来指定更新对象，并根据传过来的user信息来更新用户详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名字", required = true,paramType="path", dataType = "String"),
            @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, paramType="body",dataType = "UserEntity")
    })
	@PutMapping("/user/{userName}")
	public UserEntity edit(@PathVariable("userName") String userName,@RequestBody UserEntity user){
		UserEntity user2 = userRepository.findByUserName(userName);
		if(user2 != null){
			user.setId(user2.getId());
			userRepository.saveAndFlush(user);
		}
		return user2;
	}
	

    @ApiOperation(value="删除用户", notes="根据用户名来指定删除对象")
    @ApiImplicitParam(name = "userName", value = "用户名字", required = true,paramType="path", dataType = "String")
	@DeleteMapping("/user/{userName}")
	public UserEntity edit(@PathVariable("userName") String userName){
		UserEntity user2 = userRepository.findByUserName(userName);
		if(user2 != null){
			userRepository.delete(user2);
		}
		return user2;
	}
}
